const BASE_URL = '/api/cash/book';

export interface BillData {
  amount: number;
  remark: string;
  payUserName: string;
  forUserName: string;
  payWay: string;
  payPlat: string;
  billType: string;
  consumerDate: string;
}

export interface BillResponse {
  success: boolean;
  data: any;
  message?: string;
}

export interface BillStatistics {
  totalIncome: number;
  totalExpense: number;
  netIncome: number;
  incomeCount: number;
  expenseCount: number;
  totalCount: number;
  incomeByType: Record<string, number>;
  expenseByType: Record<string, number>;
}

// 保存账单
export const saveBill = async (data: BillData): Promise<BillResponse> => {
  const token = localStorage.getItem('token');
  const response = await fetch(`${BASE_URL}/save`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`,
    },
    body: JSON.stringify(data),
  });
  
  return response.json();
};

// 保存收入账单
export const saveIncomeBill = async (data: BillData): Promise<BillResponse> => {
  const token = localStorage.getItem('token');
  const response = await fetch(`${BASE_URL}/save/income`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`,
    },
    body: JSON.stringify(data),
  });
  
  return response.json();
};

// 保存支出账单
export const saveExpenseBill = async (data: BillData): Promise<BillResponse> => {
  const token = localStorage.getItem('token');
  const response = await fetch(`${BASE_URL}/save/expense`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`,
    },
    body: JSON.stringify(data),
  });
  
  return response.json();
};

// 查询账单列表
export const getBillList = async (params: {
  pageNumber: number;
  pageSize: number;
}): Promise<BillResponse> => {
  const token = localStorage.getItem('token');
  const queryParams = new URLSearchParams({
    pageNumber: params.pageNumber.toString(),
    pageSize: params.pageSize.toString(),
  });
  
  const response = await fetch(`${BASE_URL}/details/list?${queryParams}`, {
    method: 'GET',
    headers: {
      'Authorization': `Bearer ${token}`,
    },
  });
  
  return response.json();
};

// 查询收入账单
export const getIncomeBills = async (params: {
  pageNumber: number;
  pageSize: number;
}): Promise<BillResponse> => {
  const token = localStorage.getItem('token');
  const queryParams = new URLSearchParams({
    pageNumber: params.pageNumber.toString(),
    pageSize: params.pageSize.toString(),
  });
  
  const response = await fetch(`${BASE_URL}/income?${queryParams}`, {
    method: 'GET',
    headers: {
      'Authorization': `Bearer ${token}`,
    },
  });
  
  return response.json();
};

// 查询支出账单
export const getExpenseBills = async (params: {
  pageNumber: number;
  pageSize: number;
}): Promise<BillResponse> => {
  const token = localStorage.getItem('token');
  const queryParams = new URLSearchParams({
    pageNumber: params.pageNumber.toString(),
    pageSize: params.pageSize.toString(),
  });
  
  const response = await fetch(`${BASE_URL}/expense?${queryParams}`, {
    method: 'GET',
    headers: {
      'Authorization': `Bearer ${token}`,
    },
  });
  
  return response.json();
};

// 获取账单统计信息
export const getBillStatistics = async (): Promise<BillResponse> => {
  const token = localStorage.getItem('token');
  const response = await fetch(`${BASE_URL}/statistics`, {
    method: 'GET',
    headers: {
      'Authorization': `Bearer ${token}`,
    },
  });
  
  return response.json();
};

// 根据账单类型查询
export const getBillsByType = async (billType: string, params: {
  pageNumber: number;
  pageSize: number;
}): Promise<BillResponse> => {
  const token = localStorage.getItem('token');
  const queryParams = new URLSearchParams({
    pageNumber: params.pageNumber.toString(),
    pageSize: params.pageSize.toString(),
  });
  
  const response = await fetch(`${BASE_URL}/type/${billType}?${queryParams}`, {
    method: 'GET',
    headers: {
      'Authorization': `Bearer ${token}`,
    },
  });
  
  return response.json();
};

// 根据账单分类查询
export const getBillsByCategory = async (category: string, params: {
  pageNumber: number;
  pageSize: number;
}): Promise<BillResponse> => {
  const token = localStorage.getItem('token');
  const queryParams = new URLSearchParams({
    pageNumber: params.pageNumber.toString(),
    pageSize: params.pageSize.toString(),
  });
  
  const response = await fetch(`${BASE_URL}/category/${category}?${queryParams}`, {
    method: 'GET',
    headers: {
      'Authorization': `Bearer ${token}`,
    },
  });
  
  return response.json();
};

// 查询指定日期的账单详情
export const getBillsByDate = async (date: string): Promise<BillResponse> => {
  const token = localStorage.getItem('token');
  const response = await fetch(`${BASE_URL}/query/${date}`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
    },
  });
  
  return response.json();
};

// ========== 兼容性函数 ==========

// 兼容旧版本的saveCashBook函数
export const saveCashBook = async (formData: any): Promise<any> => {
  // 转换表单数据格式以适配新的API
  const billData: BillData = {
    amount: parseFloat(formData.amount) || 0,
    remark: formData.remark || '',
    payUserName: formData.payUserName || '',
    forUserName: formData.forUserName || '',
    payWay: formData.payWay || '',
    payPlat: formData.payPlat || '',
    billType: 'EXPENSE', // 默认为支出类型
    consumerDate: formData.consumerDate || new Date().toISOString().split('T')[0],
  };

  // 使用新的API保存账单
  return saveBill(billData);
};

// 兼容旧版本的getCashList函数
export const getCashList = async (page: number, pageSize: number): Promise<any> => {
  const token = localStorage.getItem('token');
  const queryParams = new URLSearchParams({
    pageNumber: page.toString(),
    pageSize: pageSize.toString(),
  });
  
  const response = await fetch(`${BASE_URL}/details/list?${queryParams}`, {
    method: 'GET',
    headers: {
      'Authorization': `Bearer ${token}`,
    },
  });
  
  return response.json();
};

// 兼容旧版本的expensesStatements函数
export const expensesStatements = async (params: any): Promise<any> => {
  const token = localStorage.getItem('token');
  const response = await fetch('/api/cash/book/query/statement', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`,
    },
    body: JSON.stringify(params),
  });
  
  return response.json();
};

// 兼容旧版本的updateBatch函数
export const updateBatch = async (params: any): Promise<any> => {
  const token = localStorage.getItem('token');
  const response = await fetch('/api/cash/book/update', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`,
    },
    body: JSON.stringify(params),
  });
  
  return response.json();
};

// 兼容旧版本的queryReportRecentlyAmount函数
export const queryReportRecentlyAmount = async (params: any): Promise<any> => {
  const token = localStorage.getItem('token');
  const response = await fetch('/api/report/v1', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`,
    },
    body: JSON.stringify(params),
  });
  
  return response.json();
};
